package com.listener;

import com.bean.User;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.List;

@WebListener
public class UserListener implements HttpSessionListener, HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        if ("user".equals(event.getName())) {
            //正常登录时 触发该方法
            List<User> onlineUsers = (List<User>) event.getSession().getServletContext().getAttribute("onlineUsers");
            User currentUser = (User) event.getValue();
            if (onlineUsers != null) {

            } else {
                //还没有用户名单
                onlineUsers = new ArrayList<User>();
            }
            onlineUsers.add(currentUser);
            event.getSession().getServletContext().setAttribute("onlineUsers", onlineUsers);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        if ("user".equals(event.getName())) {
            User user = (User) event.getValue();
            System.out.println(user);
            List<User> onlineUsers = (List<User>) event.getSession().getServletContext().getAttribute("onlineUsers");
            onlineUsers.remove(user);
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        //如果已经登录过用户，没有登出 且用新用户名登录，就会触发该方法
        //偷偷替换
        if ("user".equals(event.getName())) {
            //被替换的旧值 用 event.getValue();
            User user = (User) event.getValue();
            //获取在线名单
            List<User> onlineUsers = (List<User>) event.getSession().getServletContext().getAttribute("onlineUsers");
            int index = onlineUsers.indexOf(user);
            //替换后的新值 用 event.getSession().getAttribute("user");
            User newUser = (User) event.getSession().getAttribute("user");
            onlineUsers.set(index, newUser);
        }
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {

    }
}
